package cn.thoughtworks.school.services;

import cn.thoughtworks.school.entities.Notification;
import cn.thoughtworks.school.notifications.Properties;
import cn.thoughtworks.school.notifications.NotificationFactory;
import cn.thoughtworks.school.repositories.NotificationRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class NotificationService {
    private static final String STATUS_READ = "read";
    private static final String STATUS_UN_READ = "unRead";

    @Autowired
    private NotificationRepository notificationRepository;
    @Autowired
    private Properties properties;
    @Autowired
    private NotificationFactory notificationFactory;

    public List<Notification> addNotification(Map data) {
        log.info("notification data" + data);
        NotificationFactory factory = notificationFactory.factory(data, properties);
        List<Notification> notifications = factory.getNotifications();

        return notificationRepository.saveAll(notifications);
    }


    public List<Notification> getUnreadNotifications(Long userId, String status) {
        Boolean isRead = (STATUS_READ).equals(status);
        return notificationRepository.findAllByIsReadAndReceiverIdOrderByIdDesc(isRead, userId);
    }

    public Object getNotifications(Long userId, String status, Pageable pageable) {
        Boolean isRead = (STATUS_READ).equals(status);
        if (isRead) {
            return notificationRepository.findAllByIsReadAndReceiverId(isRead, userId,pageable);
        }
        return getUnreadNotifications(userId, status);
    }

    public void changeStatus(String status, Notification notification) {
        boolean needToUpdate = STATUS_UN_READ.equals(status);
        notification.setIsRead(needToUpdate);
        notificationRepository.save(notification);
    }


    public void markAll(Long userId, String status) {
        Boolean isRead = (STATUS_READ).equals(status);
        notificationRepository.updateByUserIdAndStatus(userId, isRead);
    }
}
